import 'dart:convert';

import 'package:equatable/equatable.dart';
import 'package:website.core/core/domain/entities/access_token.dart';

final _jsonBase64 = json.fuse(utf8.fuse(base64Url));

class ApiAccessTokenDto extends Equatable {
  const ApiAccessTokenDto._internal({
    required this.accessTokenData,
  });

  final String accessTokenData;

  @override
  List<Object?> get props {
    return [
      accessTokenData,
    ];
  }

  factory ApiAccessTokenDto.fromJws(String jws) {
    return ApiAccessTokenDto._internal(
      accessTokenData: jws,
    );
  }

  String _padBase64(String value) {
    final lenght = value.length;

    switch (lenght % 4) {
      case 2:
        return value.padRight(lenght + 2, '=');
      case 3:
        return value.padRight(lenght + 1, '=');
      default:
        return value;
    }
  }

  AccessToken toEntity() {
    final parts = accessTokenData.split('.');
    final payload = _jsonBase64.decode(_padBase64(parts[1])) as Map<String, dynamic>;

    final expirationTimeS = payload['exp'] as int;
    final expirationTime = DateTime.fromMillisecondsSinceEpoch(
      expirationTimeS * 1000,
      isUtc: true,
    );

    return AccessToken(
      expirationTime: expirationTime,
      data: accessTokenData,
    );
  }
}
